package com.example.movie.common.service

import android.app.Application
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.location.AMapLocationQualityReport
import com.example.movie.common.model.vm.CommonViewModel
import com.zaaach.citypicker.model.LocateState
import com.zaaach.citypicker.model.LocatedCity


/**
 * 高得地图定位服务
 */
object LocationService : Application(){

    private var locationClient: AMapLocationClient? = null
    private var locationOption: AMapLocationClientOption? = null
    private var locationHandler: Handler? = null;

    //定位监听器
    private var locationListener = AMapLocationListener { location ->
        if (null != location) {
            if (location.errorCode == 0) {
                val m = Message()
                m.what = LocateState.SUCCESS
                with(Bundle()) {
                    putString("city", location.city)
                    putString("province", location.province)
                    putString("code", location.cityCode)
                    m.data = this;
                }
                locationHandler!!.sendMessage(m)
            } else {
                getGPSStatusString(location.errorCode)?.let { Log.e("error", it) };
            }
        }
    }

    private fun getGPSStatusString(statusCode: Int): String? {
        var str = ""
        when (statusCode) {
            AMapLocationQualityReport.GPS_STATUS_OK -> str = "GPS状态正常"
            AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER -> str =
                "手机中没有GPS Provider，无法进行GPS定位"
            AMapLocationQualityReport.GPS_STATUS_OFF -> str = "GPS关闭，建议开启GPS，提高定位质量"
            AMapLocationQualityReport.GPS_STATUS_MODE_SAVING -> str =
                "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量"
            AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION -> str = "没有GPS定位权限，建议开启gps定位权限"
        }
        return str
    }

    private fun start(context: Context) {
        initLocation(context)
        locationClient?.startLocation()
    }

    private fun getDefaultOption(): AMapLocationClientOption? {
        val mOption = AMapLocationClientOption()
        mOption.locationMode =
            AMapLocationClientOption.AMapLocationMode.Hight_Accuracy //可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.isGpsFirst = false //可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.httpTimeOut = 30000 //可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.interval = 2000 //可选，设置定位间隔。默认为2秒
        mOption.isNeedAddress = true //可选，设置是否返回逆地理地址信息。默认是true
        mOption.isOnceLocation = false //可选，设置是否单次定位。默认是false
        mOption.isOnceLocationLatest =
            false //可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP) //可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.isSensorEnable = false //可选，设置是否使用传感器。默认是false
        mOption.isWifiScan =
            true //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.isLocationCacheEnable = true //可选，设置是否使用缓存定位，默认为true
        mOption.geoLanguage =
            AMapLocationClientOption.GeoLanguage.DEFAULT //可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption
    }

    private fun initLocation(context: Context) {
        locationClient = AMapLocationClient(context)
        locationOption = getDefaultOption()
        locationClient?.setLocationOption(locationOption)
        locationClient?.setLocationListener(locationListener)
    }

     fun stopLocation() {
        locationClient?.stopLocation()
    }

    fun destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient?.onDestroy()
            locationClient = null
            locationHandler = null
            locationOption = null
        }
    }

    fun startLocation(context: Context,viewModel: CommonViewModel){
        start(context)
        locationHandler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == LocateState.SUCCESS) {
                    viewModel.locatedCity.value =
                        LocatedCity(
                            msg.data.getString("city"),
                            msg.data.getString("province"),
                            msg.data.getString("code"),
                        )
                }
            }
        }

    }

}